package net.zoneland.zrdp.common.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.springframework.util.StreamUtils;

/**
 * 构建可重复读取inputStream的request
 *
 * @author zonevue
 */
public class RepeatedlyRequestWrapper extends HttpServletRequestWrapper {
    private boolean isXssRequestWrapper = false;

    public RepeatedlyRequestWrapper(final HttpServletRequest request) {
        super(request);
        HttpServletRequest currentRequest = request;
        while (currentRequest instanceof HttpServletRequestWrapper) {
            // 检查当前包装器是否是目标包装器
            if (currentRequest instanceof XssHttpServletRequestWrapper) {
                isXssRequestWrapper = true;
                break;
            }
            // 获取下一层的包装器
            currentRequest = (HttpServletRequest) ((HttpServletRequestWrapper) currentRequest).getRequest();
        }
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (isXssRequestWrapper) {
            return super.getInputStream();
        }
        final byte[] body = StreamUtils.copyToByteArray(super.getInputStream());
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new RepeatedlyServletInputStream(bais, body.length);
    }
}
